<template>
  <div class="class-management">
    <h1 class="page-title">班级管理</h1>
    
    <div class="action-bar">
      <div class="search-box">
        <el-input
          v-model="searchQuery"
          placeholder="搜索班级名称"
          prefix-icon="el-icon-search"
          clearable
          @clear="fetchClasses"
          @keyup.enter="searchClasses"
        ></el-input>
        <el-button type="primary" @click="searchClasses">搜索</el-button>
      </div>
      
      <div class="action-buttons">
        <el-button type="success" @click="showAddClassDialog">添加班级</el-button>
        <el-button type="danger" @click="showDeleteConfirm" :disabled="!hasSelection">批量删除</el-button>
      </div>
    </div>
    
    <el-table
      :data="classes"
      border
      stripe
      @selection-change="handleSelectionChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="className" label="班级名称" width="180"></el-table-column>
      <el-table-column prop="gradeLevel" label="年级" width="100"></el-table-column>
      <el-table-column prop="studentCount" label="学生数量" width="100"></el-table-column>
      <el-table-column prop="chineseTeacher" label="语文" width="100"></el-table-column>
      <el-table-column prop="mathTeacher" label="数学" width="100"></el-table-column>
      <el-table-column prop="englishTeacher" label="英语" width="100"></el-table-column>
      <el-table-column prop="physicsTeacher" label="物理" width="100"></el-table-column>
      <el-table-column prop="chemistryTeacher" label="化学" width="100"></el-table-column>
      <el-table-column prop="biologyTeacher" label="生物" width="100"></el-table-column>
      <el-table-column prop="politicsTeacher" label="政治" width="100"></el-table-column>
      <el-table-column prop="historyTeacher" label="历史" width="100"></el-table-column>
      <el-table-column prop="geographyTeacher" label="地理" width="100"></el-table-column>
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button type="primary" size="small" @click="editClass(scope.row)">编辑</el-button>
            <el-button type="info" size="small" @click="viewStudents(scope.row)">查看学生</el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="deleteClass(scope.row.id)"
            >删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    
    <!-- 添加/编辑班级对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加班级' : '编辑班级'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="classForm" :rules="rules" ref="classFormRef" label-width="100px">
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="classForm.className" placeholder="请输入班级名称"></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="gradeLevel">
          <el-select v-model="classForm.gradeLevel" placeholder="请选择年级">
            <el-option label="一年级" value="一年级"></el-option>
            <el-option label="二年级" value="二年级"></el-option>
            <el-option label="三年级" value="三年级"></el-option>
            <el-option label="四年级" value="四年级"></el-option>
            <el-option label="五年级" value="五年级"></el-option>
            <el-option label="六年级" value="六年级"></el-option>
            <el-option label="初一" value="初一"></el-option>
            <el-option label="初二" value="初二"></el-option>
            <el-option label="初三" value="初三"></el-option>
            <el-option label="高一" value="高一"></el-option>
            <el-option label="高二" value="高二"></el-option>
            <el-option label="高三" value="高三"></el-option>
          </el-select>
        </el-form-item>
        
        <el-divider>科目教师</el-divider>
        
        <el-form-item label="语文老师">
          <el-input v-model="classForm.chinese" placeholder="请输入语文老师姓名"></el-input>
        </el-form-item>
        <el-form-item label="数学老师">
          <el-input v-model="classForm.math" placeholder="请输入数学老师姓名"></el-input>
        </el-form-item>
        <el-form-item label="英语老师">
          <el-input v-model="classForm.english" placeholder="请输入英语老师姓名"></el-input>
        </el-form-item>
        <el-form-item label="物理老师">
          <el-input v-model="classForm.physics" placeholder="请输入物理老师姓名"></el-input>
        </el-form-item>
        <el-form-item label="化学老师">
          <el-input v-model="classForm.chemistry" placeholder="请输入化学老师姓名"></el-input>
        </el-form-item>
        <el-form-item label="生物老师">
          <el-input v-model="classForm.biology" placeholder="请输入生物老师姓名"></el-input>
        </el-form-item>
        <el-form-item label="政治老师">
          <el-input v-model="classForm.politics" placeholder="请输入政治老师姓名"></el-input>
        </el-form-item>
        <el-form-item label="历史老师">
          <el-input v-model="classForm.history" placeholder="请输入历史老师姓名"></el-input>
        </el-form-item>
        <el-form-item label="地理老师">
          <el-input v-model="classForm.geography" placeholder="请输入地理老师姓名"></el-input>
        </el-form-item>
        
        <el-form-item label="备注" prop="description">
          <el-input 
            type="textarea" 
            v-model="classForm.description" 
            placeholder="请输入班级备注信息"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitClassForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 查看班级学生对话框 -->
    <el-dialog
      title="班级学生列表"
      v-model="studentsDialogVisible"
      width="800px"
    >
      <div v-if="currentClass" class="class-info">
        <h3>{{ currentClass.className }}</h3>
        <p>年级: {{ currentClass.gradeLevel }}</p>
        <p>学生数量: {{ currentClass.studentCount }}</p>
      </div>
      
      <el-table
        :data="classStudents"
        border
        stripe
        v-loading="studentsLoading"
      >
        <el-table-column prop="studentId" label="学号" width="120"></el-table-column>
        <el-table-column prop="name" label="姓名" width="120"></el-table-column>
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            {{ scope.row.gender === 1 ? '男' : scope.row.gender === 2 ? '女' : '未设置' }}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

// 班级列表数据
const classes = ref([]);
const loading = ref(false);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedClasses = ref([]);
const hasSelection = computed(() => selectedClasses.value.length > 0);

// 表单相关
const dialogVisible = ref(false);
const dialogType = ref('add'); // 'add' 或 'edit'
const classFormRef = ref(null);
const classForm = reactive({
  id: null,
  className: '',
  gradeLevel: '',
  description: '',
  chinese: '',
  math: '',
  english: '',
  physics: '',
  chemistry: '',
  biology: '',
  politics: '',
  history: '',
  geography: ''
});

const rules = {
  className: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  gradeLevel: [
    { required: true, message: '请选择年级', trigger: 'change' }
  ]
};

// 教师选择相关
const teacherOptions = ref([]);
const teachersLoading = ref(false);

// 班级学生相关
const studentsDialogVisible = ref(false);
const currentClass = ref(null);
const classStudents = ref([]);
const studentsLoading = ref(false);

// 监听分页变化
watch([currentPage, pageSize], () => {
  fetchClasses();
});

// 获取班级列表
const fetchClasses = async () => {
  loading.value = true;
  try {
    const response = await axios.get('/api/admin/classes', {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        query: searchQuery.value
      }
    });
    
    if (response.data && response.data.success) {
      classes.value = response.data.data;
      total.value = response.data.total;
    } else {
      ElMessage.error(response.data.message || '获取班级列表失败');
    }
  } catch (error) {
    console.error('获取班级列表错误:', error);
    ElMessage.error('获取班级列表失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

// 搜索班级
const searchClasses = () => {
  currentPage.value = 1;
  fetchClasses();
};

// 搜索教师
const searchTeachers = async (query) => {
  if (query) {
    teachersLoading.value = true;
    try {
      const response = await axios.get('/api/admin/teachers/search', {
        params: { query }
      });
      
      if (response.data && response.data.success) {
        teacherOptions.value = response.data.data;
      } else {
        ElMessage.error(response.data.message || '搜索教师失败');
      }
    } catch (error) {
      console.error('搜索教师错误:', error);
    } finally {
      teachersLoading.value = false;
    }
  } else {
    teacherOptions.value = [];
  }
};

// 添加班级对话框
const showAddClassDialog = () => {
  dialogType.value = 'add';
  Object.keys(classForm).forEach(key => {
    classForm[key] = '';
  });
  dialogVisible.value = true;
};

// 编辑班级
const editClass = (row) => {
  dialogType.value = 'edit';
  Object.keys(classForm).forEach(key => {
    if (key in row) {
      classForm[key] = row[key];
    }
  });
  
  // 确保gradeLevel字段正确设置
  // 在检查之前打印原始数据
  console.log('编辑班级原始数据:', JSON.stringify(row, null, 2));
  
  // 确保gradeLevel字段不为空
  if (!classForm.gradeLevel) {
    console.warn('年级为空，设置默认值');
    classForm.gradeLevel = row.gradeLevel || '高一'; // 提供默认值防止null
  }
  
  console.log('设置后的年级值:', classForm.gradeLevel);
  
  // 处理教师字段，将显示字段映射到表单字段
  classForm.chinese = row.chineseTeacher === '待分配' ? '' : row.chineseTeacher;
  classForm.math = row.mathTeacher === '待分配' ? '' : row.mathTeacher;
  classForm.english = row.englishTeacher === '待分配' ? '' : row.englishTeacher;
  classForm.physics = row.physicsTeacher === '待分配' ? '' : row.physicsTeacher;
  classForm.chemistry = row.chemistryTeacher === '待分配' ? '' : row.chemistryTeacher;
  classForm.biology = row.biologyTeacher === '待分配' ? '' : row.biologyTeacher;
  classForm.politics = row.politicsTeacher === '待分配' ? '' : row.politicsTeacher;
  classForm.history = row.historyTeacher === '待分配' ? '' : row.historyTeacher;
  classForm.geography = row.geographyTeacher === '待分配' ? '' : row.geographyTeacher;
  
  console.log('编辑班级表单数据:', classForm); // 添加日志，便于排查问题
  
  dialogVisible.value = true;
};

// 提交班级表单
const submitClassForm = async () => {
  if (!classFormRef.value) return;
  
  await classFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 创建提交数据对象，确保字段名称匹配后端实体类
        const submitData = {
          id: classForm.id,
          className: classForm.className,
          grade: classForm.gradeLevel, // 显式映射gradeLevel到grade
          chinese: classForm.chinese,
          math: classForm.math,
          english: classForm.english,
          physics: classForm.physics,
          chemistry: classForm.chemistry,
          biology: classForm.biology,
          politics: classForm.politics,
          history: classForm.history,
          geography: classForm.geography,
          description: classForm.description
        };
        
        // 确保grade不为空
        if (!submitData.grade) {
          console.warn('班级年级为空，设置默认值');
          submitData.grade = '高一';
        }
        
        console.log('提交的班级数据:', JSON.stringify(submitData, null, 2));
        
        if (dialogType.value === 'add') {
          // 添加班级
          const response = await axios.post('/api/admin/class', submitData);
          if (response.data && response.data.success) {
            ElMessage.success('添加班级成功');
            dialogVisible.value = false;
            fetchClasses();
          } else {
            ElMessage.error(response.data.message || '添加班级失败');
          }
        } else {
          // 更新班级
          const response = await axios.put(`/api/admin/class/${submitData.id}`, submitData);
          if (response.data && response.data.success) {
            ElMessage.success('更新班级信息成功');
            dialogVisible.value = false;
            fetchClasses();
          } else {
            ElMessage.error(response.data.message || '更新班级信息失败');
          }
        }
      } catch (error) {
        console.error('提交班级表单错误:', error);
        ElMessage.error(error.response?.data?.message || '操作失败，请稍后重试');
      }
    } else {
      return false;
    }
  });
};

// 删除班级
const deleteClass = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该班级吗？班级内学生将不会被删除，但会失去班级关联。', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await axios.delete(`/api/admin/class/${id}`);
    if (response.data && response.data.success) {
      ElMessage.success('删除班级成功');
      fetchClasses();
    } else {
      ElMessage.error(response.data.message || '删除班级失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除班级错误:', error);
      ElMessage.error(error.response?.data?.message || '操作失败，请稍后重试');
    }
  }
};

// 查看班级学生
const viewStudents = async (classData) => {
  currentClass.value = classData;
  studentsDialogVisible.value = true;
  studentsLoading.value = true;
  
  try {
    const response = await axios.get(`/api/admin/class/${classData.id}/students`);
    if (response.data && response.data.success) {
      classStudents.value = response.data.data;
    } else {
      ElMessage.error(response.data.message || '获取班级学生失败');
    }
  } catch (error) {
    console.error('获取班级学生错误:', error);
    ElMessage.error('获取班级学生失败，请稍后重试');
  } finally {
    studentsLoading.value = false;
  }
};

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedClasses.value = selection;
};

// 批量删除确认
const showDeleteConfirm = async () => {
  if (selectedClasses.value.length === 0) {
    ElMessage.warning('请选择需要删除的班级');
    return;
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedClasses.value.length} 个班级吗？班级内学生将不会被删除，但会失去班级关联。`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const classIds = selectedClasses.value.map(c => c.id);
    const response = await axios.post('/api/admin/classes/batch-delete', { classIds });
    
    if (response.data && response.data.success) {
      ElMessage.success('批量删除成功');
      fetchClasses();
    } else {
      ElMessage.error(response.data.message || '批量删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除错误:', error);
      ElMessage.error(error.response?.data?.message || '操作失败，请稍后重试');
    }
  }
};

// 初始化
onMounted(() => {
  fetchClasses();
});
</script>

<style scoped>
.class-management {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 24px;
  color: #333;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  align-items: center;
}

.search-box {
  display: flex;
  gap: 10px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.operation-buttons {
  display: flex;
  gap: 5px;
  justify-content: flex-start;
  flex-wrap: nowrap;
}

.class-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}
</style> 